import React, { memo, useEffect, useState } from "react";
import { Table, Button, Space, Input, Drawer, Form, Row, Col, Tag } from "antd";
import { getList, addNum, addItem, del,search } from "../api/todo";
const Todo = memo(() => {
  //存放数据的数组
  const [cart, setCart] = useState([]);
  //抽屉变量
  const [open, setOpen] = useState(false);
  //初始化数据的函数
  const initCart = async () => {
    let res = await getList();
    setCart(res.data);
  };
  //组件挂载完毕后
  useEffect(() => {
    initCart();
  }, []);
  //表格头部
  const columns = [
    {
      title: "商品名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "价格",
      dataIndex: "price",
      key: "price",
    },
    {
      title: "数量",
      key: "num",
      render: (_, item) => (
        <Space size="middle">
          <Button
            onClick={async () => {
              await addNum(item.id, Number(item.num) + 1);
              initCart();
            }}
          >
            +
          </Button>
          <Input
            value={item.num}
            onChange={async (e) => {
              await addNum(item.id, Number(e.target.value));
              initCart();
            }}
          ></Input>
          <Button
            onClick={async () => {
              await addNum(item.id, item.num - 1);
              initCart();
            }}
          >
            -
          </Button>
        </Space>
      ),
    },
    {
      title: "操作",
      key: "action",
      render: (_, item) => (
        <Button
          type="primary"
          danger
          onClick={async () => {
            await del(item.id);
            initCart();
          }}
        >
          删除
        </Button>
      ),
    },
  ];
  const onFinish = async (value) => {
    let data = {};
    for (let k in value) {
      if (value[k]) {
        data[k] = value[k];
      }
    }
    await addItem({
      ...value,
      id: new Date().getTime(),
      key: new Date().getTime(),
    });
    initCart();
    addForm.setFieldsValue({ name: "", price: "", num: "" });
    setOpen(false);
  };
  const [addForm] = Form.useForm();
  const [searchForm] = Form.useForm();
  const MoneyRange = (props) => {
    const { values = ["", ""], onChange } = props;
    const [currentValue, setCurrentValue] = useState(values);
    let fromMoney = (e) => {
      const newValue = [e.target.value, currentValue[1]];
      setCurrentValue(newValue);
      onChange(newValue);
    };
    let toMoney = (e) => {
      const newValue = [currentValue[0], e.target.value];
      setCurrentValue(newValue);
      onChange(newValue);
    };
    return (
      <div>
        <Space.Compact>
          <Input
            prefix={<Tag color="#2db7f5">从</Tag>}
            value={currentValue[0]}
            suffix={<Tag color="#108ee9">元</Tag>}
            onChange={fromMoney}
          ></Input>
          <Input
            prefix={<Tag color="#2db7f5">从</Tag>}
            value={currentValue[1]}
            suffix={<Tag color="#108ee9">元</Tag>}
            onChange={toMoney}
          ></Input>
        </Space.Compact>
      </div>
    );
  };
  let SearchOnFinish =async (values) => {
    let data = {}
    for(let k in values){
      if(values[k]){
        data[k]  = values[k]
      }
    }
    if(data.price){
      data["price_gte"] = data.price[0]
      data["price_lte"] = data.price[1]
      delete data.price
    }
    console.log(data)
    let res = await search(data)
    setCart(res.data)
    // searchForm.resetFields()
  };
  return (
    <div>
      <Form form={searchForm} onFinish={SearchOnFinish}>
        <Row>
          <Col span={8}>
            <Form.Item name="name_like" label="商品名称">
              <Input placeholder="按商品名称搜索"></Input>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item name="price">
              <MoneyRange></MoneyRange>
            </Form.Item>
          </Col>
        </Row>
        <Button type="primary" htmlType="submit">
          搜索
        </Button>
        <Button onClick={()=>{searchForm.resetFields();initCart()}}>
          重置
        </Button>
      </Form>
      <Table dataSource={cart} columns={columns} />
      <Button
        type="primary"
        onClick={() => {
          setOpen(true);
        }}
      >
        添加商品
      </Button>
      <Drawer
        title="添加商品"
        placement="bottom"
        open={open}
        onClose={() => setOpen(false)}
      >
        <Form
          name="addForm"
          onFinish={onFinish}
          form={addForm}
          initialValues={{ name: "", price: "", num: "" }}
        >
          <Form.Item label="商品名称" name="name">
            <Input></Input>
          </Form.Item>
          <Form.Item label="商品价格" name="price">
            <Input></Input>
          </Form.Item>
          <Form.Item label="商品数量" name="num">
            <Input></Input>
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
              <Button type="primary" danger onClick={() => setOpen(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  );
});

export default Todo;
